package tag.in.activities;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import tag.in.Constants;
import tag.in.R;
import tag.in.TagInApplication;
import tag.in.utils.HTTPRequests;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * Register user
 * 
 * @author andre
 */
public class TagRegisterActivity extends Activity {

    private static final String CLASSTAG = TagRegisterActivity.class.getSimpleName();
    private static final int MENU_REGISTER = Menu.FIRST;
    private Button register_button;
    private EditText username;
    private EditText password;
    private EditText name;
    private EditText email;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(Constants.LOGTAG, " " + TagRegisterActivity.CLASSTAG + " onCreate");

        this.setContentView(R.layout.tag_register);

        this.username = (EditText) findViewById(R.id.username);
        this.password = (EditText) findViewById(R.id.password);
        this.name = (EditText) findViewById(R.id.name);
        this.email = (EditText) findViewById(R.id.email);
        this.register_button = (Button) findViewById(R.id.register_button);
        
        this.register_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                handleRegister();
            }
        });
    }   

    @Override
    protected void onResume() {
        super.onResume();
        Log.v(Constants.LOGTAG, " " + TagRegisterActivity.CLASSTAG + " onResume");
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, TagRegisterActivity.MENU_REGISTER, 0, R.string.add_tag_button_label).setIcon(
            android.R.drawable.ic_menu_add);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case MENU_REGISTER:
                handleRegister();
                return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }
    
    private void handleRegister() {
        if (!validate()) {
            return;
        }
        
        TagInApplication application = (TagInApplication) getApplication();
        
        HTTPRequests request = new HTTPRequests();
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("action", "register"));
        params.add(new BasicNameValuePair("id", this.username.getText().toString()));
        params.add(new BasicNameValuePair("pass", this.password.getText().toString()));
        params.add(new BasicNameValuePair("name", this.name.getText().toString()));
        params.add(new BasicNameValuePair("email", this.email.getText().toString()));
        
        int status = request.HTTPPost("http://"+application.getServerUrl()+":"+application.getServerPort()+"/"+Constants.SERVERAPP, params);
        
        /*
         * Status:	200 - OK
         * 			201 - CREATED
         * 			403 - REQUEST FAILED
         * 			500 - SERVER ERROR
         * 			501 - BAD REQUEST
         */
        if(status==201) {
        	// call next Activity, VIEW_LIST
	        Intent intent = new Intent(Constants.INTENT_ACTION_VIEW_LOGIN);
	        startActivity(intent);
        }else if(status==403){
        	new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.alert_label)).setMessage(
        		R.string.request_failed).setPositiveButton("Continuar", new DialogInterface.OnClickListener() {
		            public void onClick(final DialogInterface dialog, final int arg1) {
		            }
        		}).show();
        }else if(status==500){
        	new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.alert_label)).setMessage(
        			R.string.server_failed).setPositiveButton("Continuar", new DialogInterface.OnClickListener() {
        				public void onClick(final DialogInterface dialog, final int arg1) {
        				}
        		}).show();
        }else if(status==501){
        	new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.alert_label)).setMessage(
        			R.string.bad_request_failed).setPositiveButton("Continuar", new DialogInterface.OnClickListener() {
        				public void onClick(final DialogInterface dialog, final int arg1) {
        				}
        		}).show();
        }else if(status==0){
        	new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.alert_label)).setMessage(
        			R.string.connection_failed).setPositiveButton("Continuar", new DialogInterface.OnClickListener() {
            			public void onClick(final DialogInterface dialog, final int arg1) {
    		            }
            	}).show();
        }
    }

    // validate form fields
    private boolean validate() {
        boolean valid = true;
        StringBuilder validationText = new StringBuilder();
        if ((this.username.getText() == null) || this.username.getText().toString().equals("")
        		|| (this.password.getText() == null) || this.password.getText().toString().equals("")
        		) {
            validationText.append(getResources().getString(R.string.fill_data));
            valid = false;
        }
        if (!valid) {
            new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.alert_label)).setMessage(
                validationText.toString()).setPositiveButton("Continuar",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        // in this case, don't need to do anything other than close alert
                    }
                }).show();
            validationText = null;
        }
        return valid;
    }
}
